package com.kuaidao.common.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ReflectHelper {
    /**
     * 通过java反射，获得定义类时声明的基类(父类)的泛型参数的类型. 如类声明：public UserDao extends HibernateDao
     * 调用本方法语句getSuperClassGenericType(UserDao.class,0)返回User.class.
     *
     * @param clazz - 子类Class
     * @param index - 基类层级
     * @return 基类(父类)的泛型参数的类型
     */
    public static Class getSuperClassGenericType(final Class clazz, final int index) {
        Type genericType = clazz.getGenericSuperclass();
        if (!(genericType instanceof ParameterizedType)) {
            return Object.class;
        }
        Type[] params = ((ParameterizedType) genericType).getActualTypeArguments();


        if (index >= params.length || index < 0) {
            System.out.println("Index:" + index + ",size of " + clazz.getSimpleName()
                    + "'s Parameterize Type:" + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return (Class) params[index];
    }
}